package com.ty.web;

import com.ty.bean.Users;
import com.ty.service.UsersService;
import com.ty.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 田野
 */
@WebServlet(urlPatterns = {"/power/user/users"})
public class UsersServlet extends HttpServlet {
    UsersService usersService = new UsersServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("select".equals(method)){
            select(req, resp);
        }
    }

    // 查询数据（分页）
    protected void select(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1、接收参数(分页参数和模糊查询参数)
        String index = req.getParameter("index");
        int pageIndex = (index==null || index.length()==0)?1:Integer.parseInt(index);

        // 2、调用service层方法(需要调用两个方法：1、查询数据列表的方法 2、查询总条数的方法)
        List<Users> usersList = usersService.getUsersList(pageIndex, 5);
        int total = usersService.total();
        int totalPages = total%5 > 0 ? (total/5+1):total/5;

        // 3、存值并跳转页面
        req.setAttribute("userslist", usersList);
        req.setAttribute("pageIndex", pageIndex);
        req.setAttribute("totalPages", totalPages);
        req.setAttribute("total", total);
        req.setAttribute("size", 5);


        // 不能再"list.jsp" 前面加 / ，否则会从根目录下去找这个页面
        req.getRequestDispatcher("list.jsp").forward(req, resp);

    }

}
